package com.foolishbird.sdk.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.foolishbird.sdk.params.bean.AccountInfo;
import com.foolishbird.sdk.params.bean.ConfigInfo;
import com.foolishbird.sdk.secret.Base64;
import com.foolishbird.sdk.utils.WL;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;



public final class HttpEngineConduits {

    private static final String TAG = HttpEngineConduits.class.getSimpleName();
    private static final String FILE_NAME = "wansdksy";
    private static final int ACCOUNT_MAX_STORAGE_COUNT = 5;

    private final SharedPreferences sharedPreferences;
    private final SharedPreferences.Editor editor;
    private final List<AccountInfo> mUserAccountData;
    private final HashMap<String, Object> mCacheBuffer;

    boolean isLoggedIn = false;
    SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 缓存是否直接打开悬浮窗内容界面，数据来源登录接口返回值，默认值false
     */
    private boolean openWindowContentView;

    HttpEngineConduits(Context context) {

        sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        mUserAccountData = new ArrayList<AccountInfo>();
        mCacheBuffer = new HashMap<String, Object>();
    }

//    public final boolean isOpenWindowContentView() {
//        return openWindowContentView;
//    }
//
//    void setOpenWindowContentView(boolean openWindowContentView) {
//        this.openWindowContentView = openWindowContentView;
//    }

    public boolean isLoggedIn() {
        return isLoggedIn;
    }



    public void saveUserAccount(AccountInfo info) {
        List<AccountInfo> infos = readAllUserAccountInfo();

        if (!infos.contains(info)) {
            infos.add(0, info);
        } else {
            infos.remove(info);
            infos.add(0, info);
        }

        saveAllUserAccountInfo(infos);
    }

    public void saveAllUserAccountInfo(List<AccountInfo> accountInfos) {
        if (accountInfos != null && !accountInfos.isEmpty()) {
            final int accountSize = accountInfos.size();
            if (accountSize > ACCOUNT_MAX_STORAGE_COUNT) {
                for (int i = accountSize - 1; i > ACCOUNT_MAX_STORAGE_COUNT - 1; i--) {
                    accountInfos.remove(i);
                }
            }

            saveUserAccount();
        }
    }

    private void saveUserAccount() {
        String jsonString = new Gson().toJson(mUserAccountData);
        WL.d(TAG, "saveAllUserAccountInfo ---->jsonString: " + jsonString);
        saveUserAccount(jsonString);
    }

    private void saveUserAccount(String userAccount) {
        if (!TextUtils.isEmpty(userAccount)) {
            try {
                byte[] bytes = userAccount.getBytes("UTF-8");
                byte[] encodeBytes = Base64.encode(bytes, Base64.DEFAULT);
                String str = new String(encodeBytes, "UTF-8");

                mCacheBuffer.put("account", str);
                editor.putString("account", str);
                editor.commit();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    public AccountInfo findUserAccountByUsername(String username) {
        List<AccountInfo> infos = readAllUserAccountInfo();
        if (infos != null) {
            for (AccountInfo info : infos) {
                if (info != null && username.equals(info.getUsername())) {
                    return info;
                }
            }
        }
        return null;
    }

    public AccountInfo findUserAccountByUserId(String userId) {
        List<AccountInfo> infos = readAllUserAccountInfo();
        if (infos != null) {
            for (AccountInfo info : infos) {
                if (info != null && userId.equals(info.getUserId())) {
                    return info;
                }
            }
        }
        return null;
    }

    public List<AccountInfo> readAllUserAccountInfo() {
        if (mUserAccountData.isEmpty()) {
            String jsonString = readUserAccount();
            WL.d(TAG, "readAllUserAccountInfo ---->jsonString: " + jsonString);
            Type listType = new TypeToken<ArrayList<AccountInfo>>() {}.getType();
            List<AccountInfo> temps = new Gson().fromJson(jsonString, listType);
            if (temps != null) {
                mUserAccountData.addAll(temps);
            }
        }
        return mUserAccountData;
    }

    private String readUserAccount() {
        String accountInfo;
        if (mCacheBuffer.containsKey("account")) {
            accountInfo = (String) mCacheBuffer.get("account");
        } else {
            accountInfo = sharedPreferences.getString("account", "");
            mCacheBuffer.put("account", accountInfo);
        }

        if (!TextUtils.isEmpty(accountInfo)) {
            try {
                byte[] bytes = Base64.decode(accountInfo, Base64.DEFAULT);
                return new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public void deleteUserAccount(AccountInfo accountInfo) {
        if (mUserAccountData.contains(accountInfo)) {
            mUserAccountData.remove(accountInfo);
        }
        saveUserAccount();
    }

    public void saveCurrentLoginUserUID(String uid) {
        mCacheBuffer.put("uid", uid);
        editor.putString("uid", uid);
        editor.commit();
    }

    public String readCurrentLoginUserUID() {
        String uid = (String) mCacheBuffer.get("uid");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("uid", "");
            mCacheBuffer.put("uid", uid);
        }
        return uid;
    }


    public String readCurrentOaid(){
        String oaid = (String) mCacheBuffer.get("oaid");
        if (TextUtils.isEmpty(oaid)) {
            oaid = sharedPreferences.getString("oaid", "");
            mCacheBuffer.put("oaid", oaid);
        }
        return oaid;
    }

    public void saveCurrentLoginUserTickit(String ticket) {
        mCacheBuffer.put("ticket", ticket);
        editor.putString("ticket", ticket);
        editor.commit();
    }




    public String readCurrentLoginUserTicket() {
        String uid = (String) mCacheBuffer.get("ticket");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("ticket", "");
            mCacheBuffer.put("ticket", uid);
        }
        return uid;
    }

    public void saveGameId(String gameId) {
        mCacheBuffer.put("gameId", gameId);
        editor.putString("gameId", gameId);
        editor.commit();
    }




    public void setPlatformConfigInfo(ConfigInfo info){
//        if(info != null){
//            realnameInfo.setConfigAdultState(info.isAdult());
//        }
        mCacheBuffer.put("configInfo", info);
    }

    public ConfigInfo getPlatformConfigInfo(){
        return (ConfigInfo) mCacheBuffer.get("configInfo");
    }

    public void saveLastLoginPhoneNumber(String cellphone) {
        mCacheBuffer.put("cellphone", cellphone);
        editor.putString("cellphone", cellphone);
        editor.commit();
    }

    public String readLastLoginPhoneNumber() {
        String cellphone = (String) mCacheBuffer.get("cellphone");
        if (TextUtils.isEmpty(cellphone)) {
            cellphone = sharedPreferences.getString("cellphone", "");
            mCacheBuffer.put("cellphone", cellphone);
        }
        return cellphone;
    }

    public void writeLastLoginType(int loginType) {
        mCacheBuffer.put("loginType", loginType);
        editor.putInt("loginType", loginType);
        editor.commit();
    }

    public int readLastLoginType() {
        Object loginType = mCacheBuffer.get("loginType");
        if (loginType == null) {
            loginType = sharedPreferences.getInt("loginType", 1);
            mCacheBuffer.put("loginType", loginType);
        }
        return loginType instanceof Integer ? (Integer) loginType : 1;
    }

    public void writeAutoLogin(boolean auto){
        mCacheBuffer.put("autoLogin", auto);
        editor.putBoolean("autoLogin", auto);
        editor.commit();
    }

    public boolean readAutoLogin() {
        Object loginType = mCacheBuffer.get("autoLogin");
        if (loginType == null) {
            loginType = sharedPreferences.getBoolean("autoLogin", true);
            mCacheBuffer.put("autoLogin", loginType);
        }
        return loginType instanceof Boolean ? (Boolean) loginType : true;
    }





    public void writeNeedIdentify(boolean isAudult){
        String flow = getPlatformConfigInfo().getPopupFlow();
        if(TextUtils.isEmpty(flow)){
            flow = "";
        }
        boolean needIdentify = flow.contains("identify")?!isAudult:false;
        mCacheBuffer.put("needIdentify", needIdentify);
        editor.putBoolean("needIdentify", needIdentify);
        editor.commit();
    }

    public boolean readNeedIdentify() {
        Object loginType = mCacheBuffer.get("needIdentify");
        if (loginType == null) {
            loginType = sharedPreferences.getBoolean("needIdentify", true);
            mCacheBuffer.put("needIdentify", loginType);
        }
        return loginType instanceof Boolean ? (Boolean) loginType : true;
    }

    public void writeNeedBindPhone(boolean isAudult){

        mCacheBuffer.put("needBindPhone", isAudult);
        editor.putBoolean("needBindPhone", isAudult);
        editor.commit();
    }

    public boolean readNeedBindPhone() {
        Object loginType = mCacheBuffer.get("needBindPhone");
        if (loginType == null) {
            loginType = sharedPreferences.getBoolean("needBindPhone", true);
            mCacheBuffer.put("needBindPhone", loginType);
        }
        return loginType instanceof Boolean ? (Boolean) loginType : true;
    }


    public void saveNoMoreNotice(){

        String day = sdf1.format(new Date());
        mCacheBuffer.put("need_notice", day);
        editor.putString("need_notice", day);
        editor.commit();
    }

    public boolean readNeedNotice(){
        String historyDay;
        if(mCacheBuffer.containsKey("need_notice")){
            historyDay = (String)mCacheBuffer.get("need_notice");
//            return (int)mCacheBuffer.get("need_notice")==1;
        }else {
            historyDay = sharedPreferences.getString("need_notice","");
        }
        if(TextUtils.isEmpty(historyDay)){
            return true;
        }else {
            String day = sdf1.format(new Date());
            return  !day.equals(historyDay);
        }
    }



}
